<template>
  <div class="adjust-content-wrap">
    <SectionTitle title="申请调整内容" style="margin-bottom: 16px;" />
    <el-form
      ref="adjustContentForm"
      :label-position="showMobilePage?'left':'right'"
      :rules="rules"
      :model="formData"
      :class="{'mobile-el-form': showMobilePage}"
      class="lineHeight32"
      label-width="110px">
      <el-row type="flex" class="response-el-row">
        <template v-if="isLevelApply">
          <el-col :span="12" class="responsive-col-lg-8">
            <el-form-item label="申请客户等级" prop="customerLevelId">
              <el-select
                ref="selectClientIdRef"
                v-model="formData.customerLevelId"
                filterable
                size="small"
                clearable
                class="width240"
                placeholder="请选择客户等级"
                popper-class="global-select-down"
                @clear="onClear"
                @change="handleClientLevelChange">
                <el-option
                  v-for="item in clientLevelOptions"
                  :key="item.id"
                  :label="item.name"
                  :value="item.id"/>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12" class="responsive-col-lg-8">
            <el-form-item label="欠款额度(元)">
              <el-input v-model="formData.levelAmount" class="width240 append-input" placeholder="选择客户等级后将自动填入" size="small" disabled />
            </el-form-item>
          </el-col>
          <el-col :span="12" class="responsive-col-lg-8">
            <el-form-item label="欠款账期">
              <el-input v-model="formData.levelAccountPeriod" class="width240 append-input" placeholder="选择客户等级后将自动填入" size="small" disabled>
                <div slot="append" class="input-append-element">天</div>
              </el-input>
            </el-form-item>
          </el-col>
        </template>
        <el-col v-if="isQuotaApply" :span="12" class="responsive-col-lg-8 label-collapse-global">
          <el-form-item label="申请提升额度(元)" size="small" prop="quotaApplication">
            <el-input
              v-model="formData.quotaApplication"
              oninput="if(value>999999999999.00)value=999999999999;if(value<-999999999999.00)value=-999999999999"
              type="number"
              size="small"
              class="width240 append-input"
              placeholder="请输入申请提升额度"
              @input="handleQuotaInput"
              @change="onQuotaChange"/>
            <tipIcon content="输入正数增加额度，输入负数减少额度" style="top: 2px;" />
          </el-form-item>
        </el-col>
        <el-col v-if="isPeriodApply" :span="12" class="responsive-col-lg-8">
          <el-form-item label="申请提升账期" prop="payPeriodApplication">
            <el-input
              v-model.number="formData.payPeriodApplication"
              type="number"
              size="small"
              class="width240 append-input"
              placeholder="请输入申请提升账期"
              @input="handlePeriodInput"
              @change="onPeriodChange">
              <div slot="append" class="input-append-element">天</div>
            </el-input>
            <tipIcon content="输入正数增加账期，输入负数减少账期" style="top: 2px;" />
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
  </div>
</template>

<script>
import SectionTitle from '@/components/Title';
import { mapState } from 'vuex';
import { getLevelList } from '@/api/customer';
import { LEVEL_CHANGE_TYPE } from '@/utils/const/customer';
export default {
  components: { SectionTitle },
  props: {
    rangeList: {
      type: Array,
      default: () => ([])
    },
    detailData: {
      type: Object,
      default: () => ({})
    }
  },
  data() {
    return {
      formData: {
        customerLevelId: null,
        levelAmount: null,
        levelAccountPeriod: null,
        quotaApplication: null,
        payPeriodApplication: null
      },
      clientLevelOptions: []
    };
  },
  computed: {
    ...mapState({
      'showMobilePage': state => state.app.showMobilePage
    }),
    rules() {
      return {
        'customerLevelId': [{ required: true, message: '请选择客户等级', trigger: 'change' }],
        'quotaApplication': [{ required: true, message: '请输入申请提升额度', trigger: 'blur' }],
        'payPeriodApplication': [{ required: true, message: '请输入申请提升账期', trigger: 'blur' }]
      };
    },
    isLevelApply() {
      return this.rangeList.includes(LEVEL_CHANGE_TYPE.LEVEL);
    },
    isQuotaApply() {
      return this.rangeList.includes(LEVEL_CHANGE_TYPE.AMOUNT);
    },
    isPeriodApply() {
      return this.rangeList.includes(LEVEL_CHANGE_TYPE.PERIOD);
    }
  },
  watch: {
    detailData: {
      handler(val) {
        if (val && this.$route.params.id) {
          this.formData = val;
        }
      },
      deep: true,
      immediate: false
    },
    rangeList: {
      handler(val) {
        if (!this.isLevelApply) {
          this.formData.customerLevelId = null;
          this.formData.customerLevelName = '';
          this.formData.levelAmount = null;
          this.formData.levelAccountPeriod = null;
        }
        if (!this.isQuotaApply) this.formData.quotaApplication = null;
        if (!this.isPeriodApply) this.formData.payPeriodApplication = null;
        this.$emit('update');
      },
      deep: true
    }
  },
  created() {
    this.queryClientLevelOptions();
  },
  methods: {
    validateForm() {
      return new Promise((resolve, reject) => {
        this.$refs['adjustContentForm'].validate().then(() => {
          resolve();
        }).catch(() => {
          reject();
        });
      });
    },
    handlePeriodInput(e) {
      let value = e.replace(/[^\-\d]/g, ''); // 只能输入-和数字
      value = value.replace(/\-{2,}/g, '-'); // -只能保留一个
      value = value.replace(/(\d)\-/g, '$1'); // 数字后面不能接-，不能出现类似-11-2,12-，11-23
      value = value.replace(/-(0+)/g, '0'); // 不能出现-0,-001,-0001类似
      value = value.replace(/^0+(\d)/, '$1'); // 第一位0开头，0后面为数字，则过滤掉，取后面的数字
      value = value.replace(/(-?\d{12})\d*/, '$1'); // 最多保留12位整数
      if (value > 1000) value = 1000;
      if (value < -1000) value = -1000;
      this.formData.payPeriodApplication = Number(value) === 0 ? '' : value;
    },
    onClear() {
      this.formData.levelAmount = null;
      this.formData.levelAccountPeriod = null;
      this.$emit('update');
    },
    // 申请等级调整
    handleClientLevelChange(id) {
      if (id) {
        const res = this.clientLevelOptions.find(it => it.id === id);
        this.formData.customerLevelName = res.name;
        res.oweAmount = Number(res.oweAmount);
        res.accountPeriod = Number(res.accountPeriod);
        this.formData.levelAmount = res.oweAmount;
        this.formData.levelAccountPeriod = res.accountPeriod;
        this.$emit('update');
      }
    },
    // 申请提升账期
    onPeriodChange() {
      this.$emit('update');
    },
    // 申请提升额度
    onQuotaChange() {
      this.$emit('update');
    },
    handleQuotaInput(val) {
      if (Number(val) === 0) {
        this.$set(this.formData, 'quotaApplication', '');
      }
    },
    queryClientLevelOptions() {
      getLevelList().then(res => {
        if (res.code === 200) {
          this.clientLevelOptions = res.data || [];
        }
      });
    },
    getFormData() {
      const params = _.cloneDeep(this.formData);
      return params;
    }
  }
};
</script>

<style lang="scss" scoped>
.adjust-content-wrap {
  min-height: 90px;
}
.response-el-row {
  .width240 {
    width: 240px;
  }
  .width100 {
    width: 100%;
  }
  .append-input {
    &::v-deep {
      .el-input {
        position: relative;
      }
      .el-input__inner {
        padding-right: 25px;
        border-top-right-radius: 4px;
        border-bottom-right-radius: 4px;
      }
      .el-input-group__append {
        padding: 0;
        background-color: transparent;
        border: none;
        border-radius: 0;
      }
      .input-append-element {
        display: flex;
        align-items: center;
        height: 100%;
        position: absolute;
        right: 16px;
        top: 0;
      }
    }
  }
  ::v-deep .el-input-group--append {
    .el-input-group__append {
      color: #333;
    }
    &.is-disabled {
      .el-input-group__append {
        color: #999;
      }
    }
  }
}
.mobile-el-form {
  &::v-deep {
    .el-form-item__content {
      white-space: nowrap;
    }
  }
}
</style>
